package com.fujimana.rockincat.restree.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fujimana.rockincat.restree.init.Init;
import com.fujimana.rockincat.restree.phase.Lifecycle;
import com.fujimana.rockincat.restree.phase.Phase;

public class RestreeService implements Service {

	private Init init;

	@Override
	public void destroy() {
		this.init = null;
	}

	@Override
	public void init(Init init) {
		this.init = init;
	}

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Response.setResponse(new Response());
		
		Map<String, Object> map = new HashMap<String, Object>();

		map.put(HttpServletRequest.class.getName(), request);
		map.put(HttpServletResponse.class.getName(), response);
		map.put(Init.class.getName(), init);
		
		Message.setRepository(init.getMessageRepository());

		for (Phase phase : Lifecycle.getPhase()) {
			phase.execute(map);

			if (phase.isChain() == false) {
				break;
			}
		}

		map.clear();

		if (Response.getResponse().isRedirect()) {
			response.sendRedirect(Response.getResponse().getRedirectUri());
			return;
		}
	}

}
